<template>
  <div>
    <el-form label-width="100px" inline>
      <el-form-item label="模式：" v-if="isAuthUser()">
        <el-radio-group v-model="filters.mode">
          <el-radio-button label="lcs">比对</el-radio-button>
          <el-radio-button label="review">复习</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="单词：" v-if="filters.mode == 'lcs'">
        <el-input  v-model="filters.word" style="width:300px;" clearable @keyup.native.enter="reloadData">
          <el-select v-model="filters.type" slot="prepend" placeholder="请选择" style="width:80px;">
            <el-option label="英文" value="english"></el-option>
            <el-option label="中文" value="chinese"></el-option>
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label="相似率：" v-if="filters.mode == 'lcs'">
        <el-input-number v-model="filters.percentage" :min="0" :max="100" :step="10"  @keyup.native.enter="reloadData"></el-input-number>%
      </el-form-item>
      <el-form-item v-if="filters.mode == 'review'">
        <el-checkbox-group v-model="filters.rates">
          <el-checkbox-button :label="1">1星</el-checkbox-button>
          <el-checkbox-button :label="2">2星</el-checkbox-button>
          <el-checkbox-button :label="3">3星</el-checkbox-button>
          <el-checkbox-button :label="4">4星</el-checkbox-button>
          <el-checkbox-button :label="5">5星</el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="上次复习时间：" label-width="150px" v-if="filters.mode == 'review'">
         <el-date-picker
            v-model="filters.startDateTime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择开始时间" :picker-options="pickerOptions">
        </el-date-picker>
        <el-date-picker
            v-model="filters.endDateTime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择结束时间" :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="reloadData" :loading="loading">查询</el-button>
      </el-form-item>
      <el-form-item label="">
        <el-checkbox v-model="filters.includeDemo">添加例句</el-checkbox>
        <el-checkbox v-model="filters.isQuizMode">测验模式</el-checkbox>
      </el-form-item>
    </el-form>

    <el-table
        :data="dataList" stripe
        style="width: 100%"  @selection-change="handleSelectionChange">
    <el-table-column
          type="index"
          width="50">
      </el-table-column>
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot="header" slot-scope="scope">
          操作
          <span>
            <el-button v-if="dataList && dataList.length > 0" size="mini" @click="addPageWordList" :icon="getAddPageIcon()" round></el-button>
            <span style="display: none;">{{scope.row}}</span>
          </span>
        </template>
        <template slot-scope="scope">
          <el-button @click="addToAudioText(scope.row)" :icon="scope.row.checked ? 'el-icon-check' : 'el-icon-plus'" round></el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="isAuthUser()"
                       prop="rate"
                       label="rate" width="150">
        <template slot-scope="scope">
          <div>
            <el-rate v-model="scope.row.rate" @change="changeRate(scope.row)"></el-rate>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          prop="english" width="200"
          label="英文">
      </el-table-column>
      <el-table-column
          prop="chinese"
          label="中文">
        <template slot-scope="scope">
          <div v-if="isAuthUser()">
            <el-input
                type="textarea" style="width: 80%;"
                :rows="2"
                placeholder="请输入内容"
                v-model="scope.row.chinese">
            </el-input>
            <el-badge :is-dot="scope.row.chinese != scope.row.backupChinese">
              <el-button type="primary" style="margin-left:4px;" @click="updateChinese(scope.row)">存</el-button>
            </el-badge>
          </div>
          <div v-else>{{scope.row.chinese}}</div>
        </template>
      </el-table-column>
      <el-table-column
          prop="demo"
          label="例句">
        <template slot-scope="scope">
          <div v-if="isAuthUser()">
            <el-input
                type="textarea" style="width: 80%;"
                :rows="2"
                placeholder="请输入内容" autosize
                v-model="scope.row.demo">
            </el-input>
            <el-badge :is-dot="scope.row.demo != scope.row.backupDemo">
              <el-button type="primary" style="margin-left:4px;" @click="updateDemo(scope.row)">存</el-button>
            </el-badge>
          </div>
          <div v-else>{{scope.row.demo}}</div>
        </template>
      </el-table-column>


    </el-table>
    <el-row v-if="filters.mode == 'review'">
      <el-col :span="24" align="right">
        <el-pagination layout="total,sizes, prev, pager, next"
                       :total="total" :current-page="page"
                       :page-size="size"
                       :page-sizes="[1, 2, 3, 4, 5, 10, 15, 20, 30, 50, 100, 300, 500]"
                       @current-change="onPageChange" @size-change="onPaginationSizeChange"/>
      </el-col>
    </el-row>

    <h3 style="margin-top:20px;">单词树</h3>
    <el-tree ref="tree" v-if="showTree"
        :props="props"
        :load="loadNode"
        lazy
       :expand-on-click-node="false"
       @check-change="treeNodeCheckChange"
       show-checkbox>
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>
          <div style="display: flex;">
            <span style="flex-grow: 1" v-if="isAuthUser() && node.label != '根节点'">
              <el-rate v-model="data.rate" @change="changeRate(data)"></el-rate>
            </span>
            <span>
              {{ node.label }}
            </span>
          </div>
        </span>
      </span>
    </el-tree>
    <el-button @click="addTreeNodes" type="primary" style="margin-top:5px;">添加选中树节点({{checkedNodesLength}})</el-button>
    <h3 style="margin-top:20px;">待转换为音频文本</h3>
    <el-input
        type="textarea"
        :autosize="{ minRows: 10, maxRows: 25}"
        placeholder="请输入内容"
        v-model="audioTextValue">
    </el-input>
    <el-button @click="generateAudio" type="primary" :loading="generatingAudio" style="margin-top:5px;">生成音频</el-button>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "similar_word",
  inject: ['isAuthUser'],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      authDataKey: 'authDataKey',
      loading: false,
      generatingAudio: false,
      addAllChecked: false,
      filters: {
        mode: 'lcs',
        word: 'cat',
        type: 'english',
        percentage: 50,
        rates: [3, 4, 5],
        includeDemo: true,
        isQuizMode: false,
        startDateTime: null,
        endDateTime: null,
      },
      dataList: [],
      page: 1,
      size: 10,
      total: 0,
      audioTextValue: '',
      multipleSelection: [],
      props: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf'
      },
      treeNodeMap: {},
      showTree: true,
      checkedNodesLength: 0,
    }
  },
  methods: {
    async generateAudio() {
      this.generatingAudio = true
      let response = await axios.post('/generate_audio',
            { 
              text: this.audioTextValue, 
            }
      )
      // console.log('response:', response)
      if (response?.statusText == 'OK') {
        this.$message.success('操作成功')
        this.audioTextValue = ''
      } else {
        this.$message.error('操作失败')
      }
      this.generatingAudio = false
    },
    treeNodeCheckChange() {
      // console.log('treeNodeCheckChange:', arg1, arg2, arg3)
      this.checkedNodesLength = this.$refs.tree ? this.$refs.tree.getCheckedNodes().length : 0
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.treeNodeMap = {}
      this.showTree = false
      this.$nextTick(() => {
        this.showTree = true
      })
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: '根节点' }]);
      } else if (node.level == 1) {
        let firstLevelChildren = this.multipleSelection.map(r => {
          this.treeNodeMap[r.english] = r
          return {
            name: r.english + "(" + r.chinese + ") " + r.demo,
            chinese: r.chinese,
            english: r.english,
            demo: r.demo,
            rate: r.rate,
            id: r.id,
          }
        })
        resolve(firstLevelChildren)
        this.treeNodeCheckChange()
      } else {
        // console.log('node:', node) //node.data.name
        let authData = this.$localStorage.get(this.authDataKey)
        let token = null
        if (authData) {
          token = authData.token
        }
        axios.get('/get_similar_words',
            {  //params参数必写 , 如果没有可传参数，传{}以
              params: {
                _token: token,
                _type: this.filters.type,
                word: node.data.english,
                percentage: (this.filters.percentage || 0) / 100,
                start: 0,
                limit: 999999,
              }
            }).then(response => {
              // console.log('response:', response)
              let children = response.data.filter(r => !this.treeNodeMap[r.english]).map(r => {
                this.treeNodeMap[r.english] = r
                return {
                  name: r.english + "(" + r.chinese + ") " + r.demo,
                  chinese: r.chinese,
                  english: r.english,
                  demo: r.demo,
                  rate: r.rate,
                  id: r.id,
                  have_cache: r.have_cache,
                }
              })

              if (children && children.length > 0 && !children[0].have_cache) {
                axios.get('/update_word_relation',
                    {  //params参数必写 , 如果没有可传参数，传{}以
                      params: {
                        word: node.data.english,
                      }
                    })
              }

              resolve(children)
              this.treeNodeCheckChange()
        })
      }
    },
    addTreeNodes() {
      let checkedNodes = this.$refs.tree.getCheckedNodes()
      // console.log('checkedNodes:', checkedNodes)
      checkedNodes.forEach(n => {
        if (n.english) {
          this.addToAudioText(n)
        }
      })
    },
    getAddPageIcon() {
      return this.addAllChecked ? 'el-icon-check' : 'el-icon-plus'
    },
    onPageChange(page) {
      this.page = page
      this.loadData()
    },
    onPaginationSizeChange(val) {
      this.page = 1
      this.size = val
      this.loadData()
    },
    async changeRate(row) {
      let authData = this.$localStorage.get(this.authDataKey)
      let token = null
      if (authData) {
        token = authData.token
      }
      let response = await axios.get('/update_rate',
          {  //params参数必写 , 如果没有可传参数，传{}以
            params: {
              _token: token,
              _id: row.id,
              _rate: row.rate,
            }
          })
      // console.log('response:', response)
      if (response.data != '操作成功') {
        this.$message.error(response.data)
      } else {
        this.$message.success(response.data)
      }
    },
    addPageWordList() {
      this.addAllChecked = !this.addAllChecked
      this.dataList.forEach(r => {
        this.addToAudioText(r)
      })
    },
    addToAudioText(row) {
      let chinese = row.chinese || ''
      let splitEnglish = ''
      chinese = chinese.replaceAll('；', '.')
      // if (chinese && chinese.includes('.')) {
      //   chinese = chinese.substring(chinese.indexOf('.') + 1)
      // }
      for (let c of row.english) {
        splitEnglish += c + ' '
      }
      let demoStr = ''
      if (row.demo) {
        demoStr = row.demo + '\n'
      }
      if (this.audioTextValue) {
        this.audioTextValue += '\n'
      }
      if (this.filters.isQuizMode) {
        this.audioTextValue += '__________________ ' + chinese
      } else {
        this.audioTextValue += row.english + ' ' + splitEnglish + ' ' + row.english + ' ' + chinese
      }
      if (this.filters.includeDemo) {
        this.audioTextValue += "\n" + demoStr
      }
      this.$set(row, 'checked', true)
    },
    async updateChinese(row) {
      let response = await axios.get('/update_chinese',
          {  //params参数必写 , 如果没有可传参数，传{}以
            params: {
              _id: row.id,
              _chinese: row.chinese,
            }
          })
      // console.log('response:', response)
      if (response.data == 'ok') {
        this.$set(row, 'backupChinese', row.chinese)
      }
    },
    async updateDemo(row) {
      let response = await axios.get('/update_demo',
          {  //params参数必写 , 如果没有可传参数，传{}以
            params: {
              _id: row.id,
              _demo: row.demo,
            }
          })
      // console.log('response:', response)
      if (response.data == 'ok') {
        this.$set(row, 'backupDemo', row.demo)
      }
    },
    async reloadData() {
      this.page = 1
      await this.loadData()
    },
    async loadData() {
      this.addAllChecked = false
      if (this.filters.mode == 'lcs' && !this.filters.word) {
        this.$message.error('请输入单词')
        return
      }
      this.filters.word = this.filters.word.trim()
      this.loading = true
      let response = null
      let dataList = []
      let start = (this.page - 1) * this.size
      let limit = this.size

      let authData = this.$localStorage.get(this.authDataKey)
      let token = null
      if (authData) {
        token = authData.token
      }

      if (this.filters.mode == 'lcs') {
        response = await axios.get('/get_similar_words',
            {  //params参数必写 , 如果没有可传参数，传{}以
              params: {
                _token: token,
                _type: this.filters.type,
                word: this.filters.word,
                percentage: (this.filters.percentage || 0) / 100,
                start: 0,
                limit: 999999,
              }
            })
        // console.log('response:', response)
        dataList.push(...response.data)

        if (dataList && dataList.length > 0 && !dataList[0].have_cache) {
          axios.get('/update_word_relation',
              {  //params参数必写 , 如果没有可传参数，传{}以
                params: {
                  word: this.filters.word,
                }
              })
        }
      } else {
        response = await axios.get('/get_review_words',
            {  //params参数必写 , 如果没有可传参数，传{}以
              params: {
                _token: token,
                rates: (this.filters.rates || []).join(','),
                start_date_time: this.filters.startDateTime,
                end_date_time: this.filters.endDateTime,
                start: start,
                limit: limit,
              }
            })
        // console.log('response:', response)
        dataList.push(...response.data.data_list)
        this.total = response.data.total
      }

      dataList.forEach(r => {
        r.backupChinese = r.chinese
        r.backupDemo = r.demo
      })
      this.dataList = dataList
      this.loading = false
    },
  },
  computed: {
  },
}
</script>

<style scoped>

</style>
